using System;
using System.Collections.Generic;
using System.Linq;
using GameInit.Framework;
using TMPro;
using Unity.Netcode;
using Unity.Sync.Relay.Lobby;
using Unity.Sync.Relay.Model;
using UnityEngine;
using UnityEngine.UI;

public class SycnRalayUI : MonoBehaviour
{
    public static SycnRalayUI Instance;
    
    // --- 大厅 ---
    public GameObject Hall;
    // 创建房间
    // 房间名字
    public TMP_InputField CreateRoomName;
    // 玩家数量
    public TMP_InputField CreatePlayerMax;
    // 房间列表
    public ScrollRect ScrollViewRoomList;
    
    // --- 房间 ---
    public GameObject Room;
    // 房间名
    public TextMeshProUGUI RoomName;
    // 玩家列表
    public Transform PlayerList;
    // 开始游戏按钮
    public Button StartGameButton;
    // 准备按钮
    public Button ReadyButton;
    
    private void Start()
    {
        // 初始化单例
        Instance = this;
        // 房间默认关闭
        Room.gameObject.SetActive(false);
    }

    #region 房间
    /// <summary>
    /// 是否是房主
    /// </summary>
    private bool _isMaster;

    /// <summary>
    /// 是否全部都准备好了
    /// </summary>
    private bool _isAllReady;

    /// <summary>
    /// 自己是否准备
    /// </summary>
    private bool _isReady;
    
     /// <summary>
    /// 刷新房间信息
    /// </summary>s
    public void RefreshRoom(RelayRoom lobby,Dictionary<string,RelayPlayer> playerDic)
    {
        // 是否开始游戏
        var isStartGame = bool.Parse(lobby.CustomProperties["IsStartGame"]);
        // 没有开始游戏显示房间-开始游戏后隐藏房间 
        Room.SetActive(!isStartGame);
        // 显示房间名称
        RoomName.text = lobby.Name;
        
        // id
        var curId = UosSyncRelay.Instance.Uid;
        // 自己的网络id
        ulong curClientId = 0;
        foreach (var player in playerDic)
        {
            // log
           Debug.Log("玩家信息 "+player.Key +"," + player.Value.Name + " " +player.Value.TransportId);

           if (player.Value.ID.Equals(curId))
               curClientId = player.Value.TransportId;
        }
        
        // 主机id
        var hostId = lobby.MasterClientID;
        // 是否是主机
        _isMaster = curClientId == hostId;
        // 是否全部准备
        _isAllReady = true;
        // 刷新玩家信息
        RefreshPlayer(playerDic,hostId);
        // 刷新按钮
        RefreshRoomBtn();
    }
    
    /// <summary>
    /// 刷新玩家信息
    /// </summary>
    /// <param name="playerDic">玩家数据</param>
    /// <param name="isMaster">是否是房主</param>
    private void RefreshPlayer(Dictionary<string,RelayPlayer> playerDic,ulong masterClientID)
    {
        // 玩家数据
        var players = playerDic.Values.ToList();
        // 显示玩家
        for (int i = 0; i < PlayerList.childCount; i++)
        {
            var item = PlayerList.GetChild(i);

            if (i < players.Count)
            {
                var player =players[i];
                // 名字
                var playerName = player.Name;
                item.Find("TextPlayerName").GetComponent<TextMeshProUGUI>().text = playerName;
                // 是否是房主
                var isMaster = masterClientID == player.TransportId;
                // 不是房主显示 准备状态
                if (!isMaster)
                {
                    // 是否准备
                    var isReady = bool.Parse(player.Properties["IsReady"]);
                    item.GetComponent<Image>().color = isReady ? Color.green : Color.white;
                    
                    // 准备状态
                    _isAllReady &= isReady;
                }
                // 房主默认准备
                else 
                    item.GetComponent<Image>().color = Color.green;
            }
            
            item.gameObject.SetActive(i < playerDic.Count);
        }
    }

    /// <summary>
    /// 刷新房间按钮
    /// </summary>
    private void RefreshRoomBtn()
    {
        // 不是房主显示准备按钮
        ReadyButton.gameObject.SetActive(!_isMaster);
        ReadyButton.GetComponentInChildren<TextMeshProUGUI>().text = _isReady ? "Cancel" : "Ready";
        // 是房主并且所有玩家准备好了显示开始按钮
        StartGameButton.gameObject.SetActive(_isMaster && _isAllReady);
    }
    #endregion

    #region 大厅
    /// <summary>
    /// 创建房间
    /// </summary>
    public void CreateRoom()
    {
        // 房间名称
        var roomName = CreateRoomName.text;
        // 玩家数量
        var playerCount = int.Parse(CreatePlayerMax.text);
        // 创建房间
        UosSyncRelay.Instance.CreateRoom(roomName, playerCount, (success) =>
        {
            Debug.Log("创建房间 "+ success);
            // 隐藏大厅
            Hall.SetActive(false);
            // 启动主机
            NetworkManager.Singleton.StartHost();
        });
    }

    /// <summary>
    /// 刷新房间列表
    /// </summary>
    public void FindRoom()
    {
        var roomNameSpace = UosSyncRelay.Instance.RoomNameSpace;
        UosSyncRelay.Instance.FindRoom(roomNameSpace,0,10, RefreshRoomList);
    }

    private void RefreshRoomList(List<LobbyRoom> list)
    {
        // 没有数据隐藏
        if (list == null || list.Count == 0)
        {
            ScrollViewRoomList.content.gameObject.SetActive(false);
            return;
        }
        
        ScrollViewRoomList.content.gameObject.SetActive(true);
        // item 节点
        var content = ScrollViewRoomList.content;

        for (int i = 0; i < list.Count || i < content.childCount; i++)
        {
            // 获取房间item
            Transform item;
            if (i < content.childCount)
                item = content.GetChild(i);
            else
                item = Instantiate(content.GetChild(0),content);

            if (i < list.Count)
            {
                var lobbyRoom = list[i];
                item.GetComponentInChildren<TextMeshProUGUI>().text = lobbyRoom.Name;
                item.GetComponentInChildren<Button>().onClick.AddListener(() =>
                {
                    Debug.Log("加入房间 "+lobbyRoom.Name);
                    // 加入房间
                    JoinRoom(lobbyRoom.RoomUuid);
                    // 关闭大厅
                    Hall.gameObject.SetActive(false);
                });
            }
            
            item.gameObject.SetActive(i < list.Count);
        }
    }
    
    /// <summary>
    /// 加入房间
    /// </summary>
    /// <param name="roomUuid">房间id</param>
    private void JoinRoom(string roomUuid)
    {
        // 加入房间
        UosSyncRelay.Instance.JoinRoom(roomUuid, (success) =>
        {
            NetworkManager.Singleton.StartClient();
        });
    }

    /// <summary>
    /// 修改准备状态
    /// </summary>
    public void SetReady()
    {
        _isReady = !_isReady;
        // id
        var uId = UosSyncRelay.Instance.Uid;
        // 跟新玩家数据
        UosSyncRelay.Instance.UpdatePlayer(uId,"IsReady",_isReady.ToString());
    }
    
    /// <summary>
    /// 开始游戏
    /// </summary>
    public void StartGame()
    {
        // 跟新玩家数据
        UosSyncRelay.Instance.UpdateRoom("IsStartGame","true");
    }

    #endregion
    
    
}
